package com.wangdao.wechatmall.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: StringTransformUtils
 * @Description 对String类型的数据进行格式转化，如转为List<Integer> ，与typeHandler可以互为补充，按需要选择
 * @Author Xinhao Yi
 * @Date 2021/7/9  12:42
 */
public class StringTransformUtils {
    /*
工具函数，把字符串String"[1,2,3]"转换成List<Integer> [1,2,3]
 */
    public static List<Integer> string2IntegerList(String str) {
        //去掉头尾的 '[' 和 ']'
        str = str.substring(1, str.length() - 1);
        //用逗号把他们分割开
        String[] strList = str.split(",");
        //创建用于接受结果的List<Integer> roleIds
        List<Integer> roleIds = new ArrayList<>();
        //遍历strList进行类型转换
        for (String s : strList) {
            //类型转换
            Integer temp = Integer.parseInt(s);
            //加进来
            roleIds.add(temp);
        }
        return roleIds;
    }

    /*
    工具函数，把List<Integer> [1,2,3] 转换成字符串String"[1,2,3]"
     */
    public static String integerList2String(List<Integer> roleIds){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Integer roleId : roleIds) {
            stringBuilder.append(roleId);
            stringBuilder.append(",");
        }
        //去掉末尾多余的逗号","
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        //加上右边的]
        stringBuilder.append("]");
        String str = stringBuilder.toString();
        return str;
    }

    /*
    工具类函数，把Integer[] [1,2,3] 转换成 List<Integer> [1,2,3]
     */
    public static List<Integer> integerArray2List(Integer[] arrs){
        return Arrays.asList(arrs);
    }

    /*
    工具类函数，把List<Integer> [1,2,3]转换成 Integer[] [1,2,3]
     */
    public static Integer[] list2IntegerArray(List<Integer> list){
        Integer[] arrs = new Integer[list.size()];
        int i = 0;
        for (Integer integer : list) {
            arrs[i++] = integer;
        }
        return arrs;
    }

}
